package io.gitee.yxsnake.embark.web.core.framework.filter;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.gitee.yxsnake.embark.web.core.constant.Commons;
import io.gitee.yxsnake.embark.web.core.utils.IpUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.http.HttpMethod;

import java.io.IOException;

/**
 * @author snake
 * @description
 * @since 2024/10/18 0:14
 */
public class MDCFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String method = httpServletRequest.getMethod();
        // 放行跨域预请求
        if (HttpMethod.OPTIONS.name().toLowerCase().equals(method.toLowerCase())) {
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        }
        //如果有上层调用就用上层的ID
        String traceId = httpServletRequest.getHeader(Commons.TRACE_ID);
        if (traceId == null) {
            traceId = IdWorker.getTimeId();
        }
        MDC.put(Commons.TRACE_ID, traceId);


        String ip = IpUtil.getIpAddr(httpServletRequest);
        MDC.put(Commons.CLIENT_IP, ip);

        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    @Override
    public void destroy() {
        MDC.clear();
    }
}
